package com.aerotechnic.dao.implementation;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.aerotechnic.dao.interfaces.PlanningDaoIn;
import com.aerotechnic.entities.Outillage;
import com.aerotechnic.entities.Planning;
import com.aerotechnic.entities.Visite;

@Repository("PlanningDao")
public class PlanningDao implements PlanningDaoIn {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(Planning t) {

		// TODO Auto-generated method stub

		getCurrentSession().save(t);

	}

	@Override
	public void delete(int id) {
		// TODO Auto-generated method stub

		Planning e = findByID(id);
		if (e != null)
			getCurrentSession().delete(e);

	}

	@Override
	public Planning findByID(int id) {
		// TODO Auto-generated method stub

		Session session = sessionFactory.getCurrentSession();

		return (Planning) session.createQuery("FROM Planning where id= " + id)
				.list().get(0);
	}

	@Override
	public void update(Planning t) {
		// TODO Auto-generated method stub

		getCurrentSession().update(t);
	}

	public List<Planning> findAll() {
		// TODO Auto-generated method stub

		return getCurrentSession().createQuery("from Planning").list();
	}

	@Override
	public Planning getLastPlanning() {
		// TODO Auto-generated method stub
		return (Planning) getCurrentSession()
				.createQuery(
						"from Planning p1 where id =(select max(id) from Planning p2)")   
				.list().get(0); 
	}
}
